<template>
  <el-main>
    <el-form :model="searchObject" ref="searchForm" label-width="80px" :inline="true" size="small">
      <el-form-item>
        <el-input v-model="searchObject.roleName" placeholder="请输入角色名称" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search">查询</el-button>
        <el-button type="warning" icon="el-icon-refresh-right" @click="resetValue">重置</el-button>
        <el-button type="success" icon="el-icon-plus" @click="openAddWindow">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="roleList" :height="tableHeight" border stripe style="width: 100%; margin-bottom: 10px">
      <el-table-column prop="id" label="角色编号" width="80" align="center" sortable></el-table-column>
      <el-table-column prop="roleCode" label="角色编码" width="200" align="center"></el-table-column>
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="remark" label="角色备注"></el-table-column>
      <el-table-column label="操作选项" align="center" width="300">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button icon="el-icon-delete" type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          <el-button icon="el-icon-setting" type="primary" size="small" @click="assignRole(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      :current-page="pageNo"
      :page-size="pageSize"
      :page-sizes="[5, 10, 20, 50, 100, total]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <system-dialog :title="roleDialog.title" :visible="roleDialog.visible" :width="roleDialog.width"
                   :height="roleDialog.height" @onClose="onClose" @onConfirm="onConfirm">
      <div slot="content">
        <el-form :model="role"
                 ref="roleForm" :rules="rules" label-width="80px" :inline="false" size="small">
          <el-form-item label="角色编码" prop="roleCode">
            <el-input v-model="role.roleCode"></el-input>
          </el-form-item>
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="role.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input type="textarea" v-model="role.remark" :rows="5"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </system-dialog>

    <!-- 分配权限树窗口 -->
    <system-dialog :title="assignDialog.title" :visible="assignDialog.visible" :width="assignDialog.width"
                   :height="assignDialog.height" @onClose="onAssignClose" @onConfirm="onAssignConfirm">
      <div slot="content">
        <el-tree ref="assignTree" :data="assignTreeData" node-key="id" :props="defaultProps" empty-text="暂无数据"
                 :show-checkbox="true" :highlight-current="true" default-expand-all>
        </el-tree>
      </div>
    </system-dialog>

  </el-main>
</template>

<script>

  import roleApi from '@/api/role'
  import systemDialog from '@/components/system/systemDialog.vue'
  //导入末级节点脚本
  import leafUtils from '@/utils/leaf'
  export default {
        name: "roleList",
        components: {
            systemDialog
        },
        data(){
            return{
                rules: {
                    roleCode: [{required: true, trigger: 'blur', message: '请输入角色编码'}],
                    roleName: [{required: true, trigger: 'blur', message: '请输入角色名称'}]
                },
                roleDialog: { title: '', visible: false, height: 230, width: 500 },
                searchObject: {
                    roleName: ''
                },
                role: {id: "", roleCode: "", roleName: "", remark: "", createUser: this.$store.getters.userId},
                roleList: [],
                tableHeight: 0,
                pageNo: 1,
                pageSize: 10,
                total: 0,

                //分配权限窗口属性
                assignDialog: {title: '', visible: false, height: 450, width: 300},
                //角色ID
                roleId: '',
                //树节点数据
                assignTreeData: [],
                //树节点属性
                defaultProps: {children: 'children', label: 'label'}

            }
        },
        mounted() {
            this.$nextTick(() => {
                this.tableHeight = window.innerHeight - 220
            })
        },
        created(){
            this.search()
        },
        methods: {
            async search(pageNo = 1,pageSize = 10){
               this.searchObject.pageNo = pageNo;
               this.searchObject.pageSize = pageSize;
               let res = await roleApi.getRoleListApi(this.searchObject);
               if(res.success){
                   this.roleList = res.data.records;
                   this.total = res.data.total;
               }
            },
            resetValue(){
                this.searchObject.roleName="";
                this.search();
            },
            handleSizeChange(size){
                //将每页显示的数量交给成员变量
                this.pageSize = size;
                this.search(this.pageNo, size);
            },
            handleCurrentChange(page){
                //将当前页交给成员变量
                this.pageNo = page;
                this.search(page, this.pageSize);
            },
            handleEdit(row) {
                this.$objCopy(row, this.role);
                this.roleDialog.title = "编辑角色";
                this.roleDialog.visible = true;
            },
            async handleDelete(row) {
                let confirm = await this.$commonConfirm("确定要删除该数据吗？");
                let params = {id: row.id};
                let res = await roleApi.deleteRoleApi(params);
                if (res.success) {
                    this.$message.success(res.message);
                    this.search(this.pageNo, this.pageSize);
                } else {
                    this.$message.error(res.message)
                }
            },
            openAddWindow() {
                this.$resetForm("roleForm", this.role);
                this.roleDialog.title = '新增角色';
                this.roleDialog.visible = true;
            },
            onClose() {
                this.roleDialog.visible = false
            },
            onConfirm() {
                this.$refs.roleForm.validate(async (valid) => {
                    if (valid) {
                        let res = null;
                        if (this.role.id === '') {
                            res = await roleApi.addRoleApi(this.role);
                        }else{
                            res = await roleApi.updateRoleApi(this.role);
                        }
                        if (res.success) {
                            this.$message.success(res.message);
                            this.search(this.pageNo, this.pageSize);
                            this.roleDialog.visible = false;
                        } else {
                            this.$message.error(res.message);
                        }
                    }
                })
            },
            /**
             * 分配权限
             * @param row
             * @returns {Promise<void>}
             */
            async assignRole(row) {
                this.roleId = row.id;
                let params = {roleId: row.id, userId: this.$store.getters.userId}
                let res = await roleApi.getAssignTreeApi(params);
                if (res.success) {
                    let permissionList = res.data.permissionList;
                    let checkList = res.data.checkList;
                    let { setLeaf } = leafUtils();
                    let newPermissionList = setLeaf(permissionList);
                    this.assignTreeData = newPermissionList;
                    this.$nextTick(() => {
                        let nodes = this.$refs.assignTree.children;
                        this.setChild(nodes, checkList)
                    })
                }
                this.assignDialog.visible = true
                this.assignDialog.title = `【${row.roleName}】角色权限分配`
            },
            /**
             * 设置子节点
             * @param childNodes
             * @param checkList
             */
            setChild(childNodes, checkList) {
                if (childNodes && childNodes.length > 0) {
                    for (let i = 0; i < childNodes.length; i++) {
                        let node = this.$refs.assignTree.getNode(childNodes[i]);
                        if (checkList && checkList.length > 0) {
                            for (let j = 0; j < checkList.length; j++) {
                                if (checkList[j] === childNodes[i].id) {
                                    if (childNodes[i].open) {
                                        this.$refs.assignTree.setChecked(node, true);
                                        break
                                    }
                                }
                            }
                        }
                        if (childNodes[i].children) {
                            this.setChild(childNodes[i].children, checkList)
                        }
                    }
                }
            },
            /**
             * 分配权限窗口取消事件
             */
            onAssignClose() {
                this.assignDialog.visible = false
            },
            /**
             * 分配权限窗口确认事件
             * @returns {Promise<void>}
             */
            async onAssignConfirm() {
                //获取选中的节点key
                let ids = this.$refs.assignTree.getCheckedKeys()
                //获取选中节点的父节点id
                let pids = this.$refs.assignTree.getHalfCheckedKeys()
                //组装选中的节点ID数据
                let listId = ids.concat(pids)
                //组装参数
                let params = {roleId: this.roleId, list: listId}
                //发送请求
                let res = await roleApi.assignSaveApi(params)
                //判断是否成功
                if (res.success) {
                    //关闭窗口
                    this.assignDialog.visible = false
                    //提示成功
                    this.$message.success(res.message)
                } else {
                    //提示失败
                    this.$message.error(res.data)
                }
            }
        }
  }
</script>

<style scoped>

</style>
